// index.js
const App = getApp()
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
Page({
  data: {
    avatarUrl: defaultAvatarUrl,
    newUrl:'',
    theme: wx.getSystemInfoSync().theme,
    // 用户信息
    userInfo:{}
  },
  onLoad() {
    wx.onThemeChange((result) => {
      this.setData({
        theme: result.theme
      })
    }),
    this.getUserDetail()
  },
  getUserDetail() {
    let _this = this;
    App._get('user.index/detail', {}, function(result) {
        console.log(result);
        if(result.data.userInfo.avatarUrl != '') {
            _this.setData({
                userInfo:result.data.userInfo,
                newUrl:result.data.userInfo.avatarUrl
            })
        }else {
            _this.setData({
                newUrl:'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
            })
        }
      
    });
  },
   
  onChooseAvatar(e) {
    var that = this
    var avatarUrl = e.detail.avatarUrl
    this.setData({
      avatarUrl:avatarUrl,//让图片预览处显示刚刚选择的图片
    });
    wx.uploadFile({
      filePath: avatarUrl,
      name: 'iFile',
      url: App.api_root + 'upload/image',//服务器端接收图片的路径
      formData: {
        wxapp_id: App.getWxappId(),
        token: wx.getStorageSync('token')
      },
      success:function(res){
        console.log(res);//发送成功回调
        let result = typeof res.data === "object" ? res.data : JSON.parse(res.data);
        // console.log(result.data.file_path);
            that.setData({
                newUrl:result.data.file_path
            })
      },
      fail:function(res){
        console.log(res);//发送失败回调，可以在这里了解失败原因
      }
    })
},
  formSubmit(e){
      console.log(e.detail.value.nickname);
    App._post_form('user/edit', {
        nickName:e.detail.value.nickname,
        avatarUrl:this.data.newUrl
    }, function(result) {
        // console.log(result);
        wx.showToast({
            title:"保存成功",
           icon:"success"
        })
        setTimeout(() => {
            wx.switchTab({
                url: '/pages/user/index',
            })
        }, 1500);
        
    });
  }
})
